package com.llm.travel_agent_assistant.interceptor; // 确保包路径正确

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 目标方法执行前执行（核心拦截逻辑）
     * @return true：放行（允许访问目标方法）；false：拦截（阻止访问）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取Session（或Token，根据你的登录机制选择）
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("userId");

        // 2. 判断用户是否已登录
        if (loginUser == null) {
            // 未登录：拦截
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"请先登录\"}");
            return false; // 拦截
        }

        // 3. 已登录：放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}